package andy.ham;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.text.DateFormat;
import java.util.Date;

import andy.ham.DaoMaster.DevOpenHelper;

public class DiaryEditor extends Activity {

	private static final String TAG = "Diary";
	public static final String EDIT_DIARY_ACTION = "andy.ham.DiaryEditor.EDIT_DIARY";
	public static final String INSERT_DIARY_ACTION = "andy.ham.DiaryEditor.action.INSERT_DIARY";

	// GreenDAO使用的变量
	private SQLiteDatabase db;
	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private NoteDao noteDao;
	private Note note;

	private static final int STATE_INSERT = 1;
	private int mState;

	private EditText mTitleText;
	private EditText mBodyText;
	private Button confirmButton;
	private Button cancelButton;
	private long mid;
	String TITLE;
	String BODY;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(android.R.style.Theme_Black);
		final Intent intent = getIntent();
		final String action = intent.getAction();
		setContentView(R.layout.diary_edit);

		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);
		confirmButton = (Button) findViewById(R.id.confirm);
		cancelButton = (Button) findViewById(R.id.cancel);

		initDAO();
		Log.d("action", action);

		if (EDIT_DIARY_ACTION.equals(action))
		{
			Bundle bundle = new Bundle(this.getIntent().getExtras());
			mid = bundle.getLong("id");
			note = noteDao.loadByRowId(mid);
			TITLE=note.getTitle();
			BODY=note.getBody();
			mTitleText.setTextKeepState(TITLE);//保持光标原来的位置
			mBodyText.setTextKeepState(BODY);//setText会使光标回到起点
			setTitle("编辑日记");
		}
		else if (INSERT_DIARY_ACTION.equals(action))
		{
			mState = STATE_INSERT;
			setTitle("新建日记");
		}
		else
		{
			Log.e(TAG, "no such action error");
			finish();
			return;
		}
		confirmButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View view)
			{
				boolean k;
				if (mState == STATE_INSERT)
				{
					k=insertDiary();
					if(k)
					{
						Intent intent = new Intent(DiaryEditor.this, LifeDiary.class);
						startActivity(intent);
						DiaryEditor.this.finish();
					}
				}
				else
				{
					k=updateDiary();
					if(k)
					{
						Intent intent = new Intent(DiaryEditor.this, LifeDiary.class);
						startActivity(intent);
						DiaryEditor.this.finish();
					}
				}
			}
		});
		cancelButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View view)
			{
				Intent intent = new Intent(DiaryEditor.this, LifeDiary.class);
				startActivity(intent);
				DiaryEditor.this.finish();
			}
		});
	}

	private void initDAO() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		noteDao = daoSession.getNoteDao();
	}

	private boolean insertDiary()
	{
		String title = mTitleText.getText().toString();
		String body = mBodyText.getText().toString();
		final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
		String date = df.format(new Date());
		String[] columns=new String[]{"TITLE"};
		Cursor c=db.query(noteDao.getTablename(),columns,null,null,null,null,null,null);
		int j=0;
		if(c.moveToFirst())
		{
			do
			{
				String name=c.getString(c.getColumnIndex("TITLE"));
				if(title.equals(name))
				{
					j=1;
				}
			}while(c.moveToNext());
		}
		if(title.equals("")||j==1)
		{
			if(title.equals(""))
			{
				Toast.makeText(this,"标题不能为空，请输入标题",Toast.LENGTH_SHORT).show();
				return false;
			}
			else if(j==1)
			{
				Toast.makeText(this,"标题重复，请重新输入",Toast.LENGTH_SHORT).show();
				return false;
			}
			return false;
		}
		else
		{
			Note note = new Note(null, title, body, date);
			noteDao.insert(note);
			Log.d("DaoExample", "Inserted new note, ID: " + note.getId());
			return true;
		}
	}

	private boolean updateDiary() {
		String title = mTitleText.getText().toString();
		String body = mBodyText.getText().toString();
		final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
		String date = df.format(new Date());
		noteDao.deleteByKey(mid);
		String[] columns=new String[]{"TITLE"};
		Cursor c=db.query(noteDao.getTablename(),columns,null,null,null,null,null,null);
		int j=0;
		if(c.moveToFirst())
		{
			do
			{
				String name=c.getString(c.getColumnIndex("TITLE"));
				if(title.equals(name))
				{
					j=1;
				}
			}while(c.moveToNext());
		}
		if(title.equals("")||j==1)
		{
			if(title.equals(""))
			{
				Toast.makeText(this,"标题不能为空，请输入标题",Toast.LENGTH_SHORT).show();
				Note note = new Note(null, TITLE, BODY, date);
				noteDao.insert(note);
				return false;
			}
			else if(j==1)
			{
				Toast.makeText(this,"标题重复，请重新输入",Toast.LENGTH_SHORT).show();
				Note note = new Note(null, TITLE, BODY, date);
				noteDao.insert(note);
				return false;
			}
			return false;
		}
		else
		{
			Note note = new Note(null, title, body, date);
			noteDao.insert(note);
			return true;
		}
	}

}
